﻿Imports System.IO
Imports SACommon

Public Class ucApplication
    Private mUpdateAppItem As UpdateAppItem

    Private mDirectory As AppDirectory
    Private mDirectoryID As Integer
    Private mMainDirectoryExists As Boolean
    Private mFileDirectoryExists As Boolean
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        ResetFTPFields()
    End Sub
    Private Sub ucApplication_Load(sender As Object, e As EventArgs) Handles Me.Load
        LoadCategories()
        ResetFields()

        lblInstallerMD5.Text = ""
        lblHelpMD5.Text = ""

        mDirectory = New AppDirectory
        If gUDApp.SelectedAppID = 0 Then
            mDirectory.add("<%APPDIR%>\")
            btnAppAdd.Text = "Add"
            lblAppHeader.Text = "New Application"
        Else
            btnAppAdd.Text = "Update"
            lblAppHeader.Text = "Update Application: " & txtAppDescription.Text
        End If

        mUpdateAppItem = gUDApp.SelectedApp
        SetVariableDefaults()
        gApp.SetAppVariables()
        LoadDirectories()
    End Sub

#Region "General Loading"
    Sub LoadCategories()
        cmbCategory.DataSource = gCat.CategoryList
        cmbCategory.SelectedIndex = 0
    End Sub
#End Region
#Region "Process UI"
    Private Sub btnAppAdd_Click(sender As Object, e As EventArgs) Handles btnAppAdd.Click
        AssignVariableValues()

        gUDApp.SelectedAppID = gUDApp.Save(mUpdateAppItem)
        gApp.SetAppVariables()

        Messenger.SendMessage(Messenger.MessageType.UpdateEnd, txtAppDescription.Text.Trim & " Saved", True)
        Messenger.SendMessage(Messenger.MessageType.AppSelected, "", True)
    End Sub
    Private Sub btnAppCancel_Click(sender As Object, e As EventArgs) Handles btnAppCancel.Click
        ResetFields()
    End Sub
    Private Sub chkShowPassword_CheckedChanged(sender As Object, e As EventArgs) Handles chkShowPassword.CheckedChanged
        If chkShowPassword.Checked = False Then
            txtFTPPassword.PasswordChar = "*"
        Else
            txtFTPPassword.PasswordChar = ""
        End If
    End Sub
    Private Sub btnCreateDef_Click(sender As Object, e As EventArgs) Handles btnCreateDef.Click
        Dim tName As String
        Dim saveFileDialog1 As New SaveFileDialog() With {.Filter = "txt files (*.udf)|*.udf",
                                                          .FilterIndex = 2,
                                                          .RestoreDirectory = True}

        If saveFileDialog1.ShowDialog() = DialogResult.OK Then
            tName = saveFileDialog1.FileName
            UpdateCore.WriteAppDefinitionFile(tName)
        End If
    End Sub
    Private Sub btnCategories_Click(sender As Object, e As EventArgs) Handles btnCategories.Click
        Messenger.SendMessage(Messenger.MessageType.CategoryEdit, "", True)
    End Sub
    Private Sub btnFTPCreate_Click(sender As Object, e As EventArgs)
        AddFTPDirectory()
    End Sub
    Private Sub btnStopAll_Click(sender As Object, e As EventArgs) Handles btnStopAll.Click
        StopAllUpdates()
    End Sub
    Private Sub btnGoToVersions_Click(sender As Object, e As EventArgs) Handles btnGoToVersions.Click
        Messenger.SendMessage(Messenger.MessageType.ChangePage, "Version", True)
    End Sub
    Private Sub btnFTPCheck_Click(sender As Object, e As EventArgs) Handles btnFTPCheck.Click
        If txtFTPServer.Text.Trim = "" Then
            Messenger.SendMessage(Messenger.MessageType.GeneralMessage, "Please specify a valid FTP Server", True)
            Exit Sub
        End If

        If txtFTPUsername.Text.Trim = "" Then
            Messenger.SendMessage(Messenger.MessageType.GeneralMessage, "Please specify a valid username", True)
            Exit Sub
        End If

        If txtFTPPassword.Text.Trim = "" Then
            Messenger.SendMessage(Messenger.MessageType.GeneralMessage, "Please specify a valid password", True)
            Exit Sub
        End If

        If UpdateCore.Connected(True) = False Then
            Messenger.SendMessage(Messenger.MessageType.GeneralMessage, "Please connect to the internet", True)
            Exit Sub
        End If

        Messenger.SendMessage(Messenger.MessageType.WaitformOpen, "", True)
        Messenger.SendMessage(Messenger.MessageType.WaitFormMessage, "Checking Respository Server Folders ...", True)

        Messenger.SendMessage(Messenger.MessageType.UpdateStart, "Checking Respository Server Folders ...", True)

        Dim tSuccess As Boolean = CheckFTPDirectory()

        Messenger.SendMessage(Messenger.MessageType.WaitFormClose, "", True)

        Messenger.SendMessage(Messenger.MessageType.UpdateEnd, "", True)

        If tSuccess = False Then
            Messenger.SendMessage(Messenger.MessageType.UpdateEnd, "Please create Respository Server Folders ...", True)
            btnFTPCreate.Visible = True
            Exit Sub
        End If
    End Sub
#End Region
#Region "General Functions"
    Sub ResetFields()
        cmbCategory.SelectedIndex = 0
        txtAppDescription.Text = ""
        txtAppRepository.Text = ""
        lblCreatedOn.Text = ""
        btnGoToVersions.Visible = False
    End Sub
    Function CheckFTPDirectory() As Boolean
        ResetFTPFields()

        Dim fd As New FTPFunctions(FTPMainUpdateFolder, mUpdateAppItem.FTPUsername, mUpdateAppItem.FTPPassword)
        Dim responseString = fd.CheckFTPDirectory
        If responseString <> "" Then
            pbFTPDirectory.Image = My.Resources._Error
            lblFTPResponse.Text = responseString
            btnFTPCreate.Visible = True
            mMainDirectoryExists = False
            Return False
        Else
            mMainDirectoryExists = True
        End If

        fd = New FTPFunctions(FTPFileUpdateFolder, mUpdateAppItem.FTPUsername, mUpdateAppItem.FTPPassword)
        responseString = fd.CheckFTPDirectory
        If responseString <> "" Then
            pbFTPDirectory.Image = My.Resources._Error
            lblFTPResponse.Text = responseString
            btnFTPCreate.Visible = True
            mFileDirectoryExists = False
            Return False
        Else
            pbFTPDirectory.Image = My.Resources.ok_button
            mFileDirectoryExists = True
        End If

        Return True
    End Function
    Private Function FTPMainUpdateFolder() As String
        Return UpdateCore.FixURLText(mUpdateAppItem.FTPServerURL & mUpdateAppItem.RepositoryFolder)
    End Function
    Private Function FTPFileUpdateFolder() As String
        Return UpdateCore.FixURLText(String.Format("{0}{1}/UpdateFiles", mUpdateAppItem.FTPServerURL, mUpdateAppItem.RepositoryFolder))
    End Function
    Function AddFTPDirectory() As Boolean
        ResetFTPFields()
        Dim responseString As String

        If mMainDirectoryExists = False Then
            Dim fmd As New FTPFunctions(FTPMainUpdateFolder, mUpdateAppItem.FTPUsername, mUpdateAppItem.FTPPassword)
            responseString = fmd.CreateFTPDirectory
            If responseString <> "" Then
                pbFTPDirectory.Image = My.Resources._Error
                lblFTPResponse.Text = responseString
                btnFTPCreate.Visible = True
                mMainDirectoryExists = False
                Return False
            Else
                mMainDirectoryExists = True
            End If
        End If

        Dim fd As New FTPFunctions(FTPFileUpdateFolder, mUpdateAppItem.FTPUsername, mUpdateAppItem.FTPPassword)
        responseString = fd.CreateFTPDirectory
        If responseString <> "" Then
            pbFTPDirectory.Image = My.Resources._Error
            lblFTPResponse.Text = responseString
            btnFTPCreate.Visible = True
            mFileDirectoryExists = False
            Return False
        Else
            pbFTPDirectory.Image = My.Resources.ok_button
            mFileDirectoryExists = True
        End If

        Return True
    End Function
    Sub ResetFTPFields()
        pbFTPDirectory.Image = Nothing
        btnFTPCreate.Visible = False
        lblFTPResponse.Text = ""
    End Sub
    Shared Sub StopAllUpdates()
        Dim verFile As New UpdateCore.UpdateVersion() With {.Allow = False,
                                                            .CoreVersion = "",
                                                            .CoreIsBeta = False,
                                                            .CoreType = "",
                                                            .InstallerVersion = "",
                                                            .InstallerMD5 = "",
                                                            .HelpVersion = "",
                                                            .HelpMD5 = ""}
        verFile.WriteVersionFile(gApp.UpdateVersionFile)
    End Sub
    Sub SetVariableDefaults()
        If gUDApp.SelectedAppID <> 0 Then mDirectory.ItemList = mUpdateAppItem.DirectoryList
        txtAppDescription.Text = mUpdateAppItem.ApplicationTitle
        txtAppRepository.Text = mUpdateAppItem.RepositoryServerURL
        txtInstallerVersion.Text = mUpdateAppItem.InstallerVersion
        txtHelpVersion.Text = mUpdateAppItem.HelpVersion
        lblCreatedOn.Text = DateFunctions.GetDateTimeFromString(mUpdateAppItem.DateTimeCreated).ToString("D")
        txtFTPServer.Text = mUpdateAppItem.FTPServerURL
        txtFTPUsername.Text = mUpdateAppItem.FTPUsername
        txtFTPPassword.Text = mUpdateAppItem.FTPPassword
        txtRepositoryFolder.Text = mUpdateAppItem.RepositoryFolder
        cmbCategory.SelectedValue = mUpdateAppItem.CategoryID
        lblInstallerMD5.Text = mUpdateAppItem.InstallerMD5
        lblHelpMD5.Text = mUpdateAppItem.HelpMD5
    End Sub
    Private Sub AssignVariableValues()
        mUpdateAppItem.ApplicationTitle = txtAppDescription.Text.Trim
        mUpdateAppItem.RepositoryServerURL = UpdateCore.FixURLText(txtAppRepository.Text.Trim)
        mUpdateAppItem.CategoryID = cmbCategory.SelectedValue
        mUpdateAppItem.DirectoryList = mDirectory.ItemList
        mUpdateAppItem.InstallerVersion = txtInstallerVersion.Text
        mUpdateAppItem.RepositoryFolder = UpdateCore.FixURLText(txtRepositoryFolder.Text.Trim)
        mUpdateAppItem.FTPPassword = txtFTPPassword.Text.Trim
        mUpdateAppItem.FTPServerURL = UpdateCore.FixURLText(txtFTPServer.Text.Trim)
        mUpdateAppItem.HelpVersion = txtHelpVersion.Text.Trim
        mUpdateAppItem.FTPUsername = txtFTPUsername.Text.Trim
        UpdateCore.RepositoryServer = mUpdateAppItem.RepositoryServerURL
        UpdateCore.RepositoryFolder = mUpdateAppItem.RepositoryFolder
    End Sub
#End Region
#Region "Directories"
    Private Sub btnDirAdd_Click(sender As Object, e As EventArgs) Handles btnDirAdd.Click
        Dim tString As String = txtAppDirectory.Text.Trim
        If Strings.Left(tString, 1) <> "\" Then tString &= "\"
        tString = "<%APPDIR%>" & tString
        If Strings.Right(tString, 1) <> "\" Then tString = tString & "\"

        If mDirectoryID <> 0 Then
            Dim t = (From x In mDirectory.ItemList Where x.DirectoryID = mDirectoryID).First
            t.Directory = tString
        Else
            mDirectory.add(tString)
        End If
        LoadDirectories()
    End Sub
    Sub LoadDirectories()
        Dim itm As ListViewItem
        lvwDirectories.Groups.Clear()
        lvwDirectories.Items.Clear()
        'Add items
        For Each item In mDirectory.ItemList
            itm = New ListViewItem With {.ImageIndex = 0, .Text = item.Directory, .Tag = item.DirectoryID}
            lvwDirectories.Items.Add(itm)
        Next
    End Sub
    Private Sub lvwDirectories_Click(sender As Object, e As EventArgs) Handles lvwDirectories.Click
        mDirectoryID = 0
        If lvwDirectories.SelectedItems.Count > 0 Then
            mDirectoryID = CInt(lvwDirectories.SelectedItems(0).Tag)
            txtAppDirectory.Text = (From x In mDirectory.ItemList Where x.DirectoryID = mDirectoryID).First.Directory
            btnDirAdd.Text = "Update"
        End If
    End Sub
#End Region
#Region "Installer"
    Private Sub btnUploadInstaller_Click(sender As Object, e As EventArgs) Handles btnUploadInstaller.Click
        Dim tResult As SAEventArgs = ChooseInstallerFiles()
        If tResult.Result = SAEventArgs.Results.Success Then
            Messenger.SendMessage(Messenger.MessageType.WaitFormMessage, "Completing Installer Update ...", True)

            Dim tUpdateAppItem = gUDApp.SelectedApp
            tUpdateAppItem.InstallerMD5 = tResult.Message
            gUDApp.Save(tUpdateAppItem)
            lblInstallerMD5.Text = tUpdateAppItem.InstallerMD5

            Messenger.SendMessage(Messenger.MessageType.WaitFormClose, "", True)
            Messenger.SendMessage(Messenger.MessageType.GeneralMessage, "Updater sucessfully updated.", True)

            btnGoToVersions.Visible = True
        End If
    End Sub
    Function ChooseInstallerFiles() As SAEventArgs
        Dim tMD5 As String
        Dim tFilename As String

        Dim tResult As SAEventArgs = New SAEventArgs("", SAEventArgs.Results.GeneralFailure)
        Dim openFileDialog1 As OpenFileDialog = New OpenFileDialog() With {.Filter = "Installer Files (Updater.exe)|Updater.exe",
                                                                           .FilterIndex = 1,
                                                                           .Multiselect = False,
                                                                           .CheckFileExists = True,
                                                                           .CheckPathExists = True}
        Dim UserClickedOK As Boolean = openFileDialog1.ShowDialog

        If (UserClickedOK = True) And (openFileDialog1.FileNames.Count > 0) Then
            Messenger.SendMessage(Messenger.MessageType.WaitformOpen, "", True)

            Messenger.SendMessage(Messenger.MessageType.WaitFormMessage, "Preparing Installer for Upload ...", True)
            tFilename = openFileDialog1.FileName
            txtInstallerVersion.Text = FileVersionInfo.GetVersionInfo(tFilename).FileVersion
            tMD5 = CompressInstallerFiles(tFilename)

            Messenger.SendMessage(Messenger.MessageType.WaitFormMessage, "Uploading Installer files ...", True)
            tResult = UploadInstallerFiles(tMD5.Trim)
        End If
        Return tResult
    End Function
    Function CompressInstallerFiles(Filename As String) As String
        Dim tCompressedMD5 As String
        Dim tDestinationFilename As String = String.Format("{0}{1}", gApp.DataDirectory, "Updater.exe")
        'Copy SAUpdater.exe to the archive folder
        If Directory.Exists(gApp.DataDirectory) = False Then Directory.CreateDirectory(gApp.DataDirectory)
        Do While File.Exists(tDestinationFilename)
            File.Delete(tDestinationFilename)
            Application.DoEvents()
        Loop
        File.Copy(Filename, tDestinationFilename)

        Dim tOriginFilename As String = tDestinationFilename
        'This is a workaround to make Sharpcompress LZMA work
        tDestinationFilename = gApp.TempDirectory & "Updater.exe"
        If Directory.Exists(gApp.TempDirectory) = False Then Directory.CreateDirectory(gApp.TempDirectory)
        Do While File.Exists(tDestinationFilename)
            File.Delete(tDestinationFilename)
            Application.DoEvents()
        Loop
        File.Copy(tOriginFilename, tDestinationFilename)

        Do
            Application.DoEvents()
        Loop Until File.Exists(tDestinationFilename) = True
        'Create the zip
        tOriginFilename = tDestinationFilename

        tDestinationFilename = String.Format("{0}{1}.ZIP", gApp.DataDirectory, "SACU")
        tCompressedMD5 = Utils.ArchiveFile(tDestinationFilename, False)
        Application.DoEvents()
        File.Delete(tOriginFilename)
        Do
            Application.DoEvents()
        Loop Until File.Exists(tOriginFilename) = False
        Return tCompressedMD5
    End Function
    Function UploadInstallerFiles(MD5 As String) As SAEventArgs
        Dim tOriginFilename As String = String.Format("{0}{1}.ZIP", gApp.DataDirectory, "SACU")
        If Utils.DoDataUpload(tOriginFilename, gApp.FTPMainUpdateFolder & "/SACU.ZIP") = False Then
            Return New SAEventArgs("Upload failed!", SAEventArgs.Results.GeneralFailure)
        End If
        tOriginFilename = String.Format("{0}{1}", gApp.DataDirectory, "Updater.exe")
        If Utils.DoDataUpload(tOriginFilename, gApp.FTPMainUpdateFolder & "/Updater.exe") = False Then
            Return New SAEventArgs("Upload failed!", SAEventArgs.Results.GeneralFailure)
        End If
        Return New SAEventArgs(MD5, SAEventArgs.Results.Success)
    End Function
#End Region



End Class
